<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>005 统计次数</title>
</head>
<body>

  <h1>005 统计次数</h1>
  <p>统计 "a" 在字符串中出现的次数</p>
  <p>如 "asdfssaaasasasasaa" 中，"a" 出现的次数。</p>

  <form id="myform" method="get">
    <input type="text" name="str" value="asdfssaaasasasasaa" placeholder="请随机输入内容...">
    <input type="submit" value="统计">
  </form>

  <script>
    document.getElementById("myform").addEventListener("submit", function(e) {

      //阻止默认提交行为.
      e.preventDefault();

      //获取 a 出现次数.
      var result = this.str.value.match(/a/g).length;

      //非空验证，为空不再继续.
      if( result <= 0 ) { return; }

      //通知结果.
      alert("a 共出现 " + result + " 次");

    }, false);
  </script>

</body>
</html>
